import React from "react";
import {
  Row,
  Col,
  Form,
  Input,
  Button,
  DatePicker,
  Select /* , Dropdown */,
} from "antd";
import Zcon from "@cbd/icon";
import UserSelectModal from "components/userSelectModal/UserSelectModal";
import CustomTreeSelectField from "components/customTreeSelectField";
import styles from "./AdvancedFilter.less";

const { RangePicker } = DatePicker;
const { Option } = Select;

const statusConfig = [
  { label: "正常", value: "NORMAL" },
  { label: "预警", value: "WARNING" },
  { label: "超时", value: "TIMEOUT" },
  { label: "终止", value: "END" },
  { label: "撤办", value: "RECALL" },
  { label: "暂停", value: "PAUSE" },
  { label: "错误", value: "ERROR" },
];
const progressConfig = [
  { label: "启动", value: "START" },
  { label: "进行中", value: "RUNNING" },
  { label: "结束", value: "END" },
];
const taskConfig = [
  { label: "待处理", value: "TODO" },
  { label: "已处理", value: "DONE" },
];

@Form.create()
class AdvancedFilter extends React.Component {


  state = {
    checkedNodes : [],
    checkedKeys: [],
    checkedOrgNodes : [],
    checkedOrgKeys: [],
    checkedPosNodes : [],
    checkedPosKeys: [],
    overlayVisible: false,
    selectUserType: '', // 选人组件需多处调用，此为判别字段
    selectedType: '',
    selectedName:'',
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  componentDidMount() {
    const { getFormThis } = this.props;
    if (getFormThis) getFormThis(this, "advancedFilter");
  }

  handleReset = () => {
    this.setState({ checkedNodes:[], checkedKeys: [],checkedOrgKeys:[], checkedOrgNodes:[], checkedPosNodes : [], checkedPosKeys: []});
    const { form } = this.props;
    form.resetFields();
  };

  handleSubmit = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, handleParamsChange, renderType = "flow" } = this.props;
    const { checkedOrgKeys } = this.state;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const { datatime } = values;
      const param = { ...values };
      delete param.datatime;
      if (datatime && datatime.length > 0) {
        param.timeStart = datatime[0].format("YYYY-MM-DD HH:mm:ss");
        param.timeEnd = datatime[1].format("YYYY-MM-DD HH:mm:ss");
      } else if (renderType === "flow" || renderType === "rule") {
        param.timeStart = "";
        param.timeEnd = "";
      }

      const { endDatatime } = values;
      delete param.endDatatime;
      if (endDatatime && endDatatime.length > 0) {
        param.endTimeStart = endDatatime[0].format("YYYY-MM-DD HH:mm:ss");
        param.endTimeEnd = endDatatime[1].format("YYYY-MM-DD HH:mm:ss");
      } else if (renderType === "flow" || renderType === "rule") {
        param.endTimeStart = "";
        param.endTimeEnd = "";
      }

      if (values.applyUserNames) {
        param.applyUserNames = values.applyUserNames.split(/,|，/);
      } else if (values.applyUserNames === "") {
        param.applyUserNames = [];
      }

      if (values.operatorUserNames) {
        param.operatorUserNames = values.operatorUserNames.split(/,|，/);
      } else if (values.operatorUserNames === "") {
        param.operatorUserNames = [];
      }
      if (values.orgStr){
        param.orgStr = checkedOrgKeys.join(',');
      }
      if (values.roleIdStr){
        param.roleIdStr = values.roleIdStr.map(v => v.value).join(',');
      }
      if (values.operator) {
        param.operator = values.operator.split(/,|，/);
      } else if (values.operator === "") {
        param.operator = [];
      }
      if (handleParamsChange) handleParamsChange(param);
    });
  };

  handleSearch = () => {
    const { onSearch } = this.props;
    if (onSearch instanceof Function) onSearch();
  };

  checkTree = (checkedKeys, checkedNodes) => {
    const { form } = this.props;
    const { selectUserType, selectedType} = this.state;
    const value = checkedNodes
      .map((item) => {
        const { props } = item;
        return props.title;
      })
      .join("，");
    if (selectedType === 'organ'){
      this.setState({ checkedOrgKeys:checkedKeys, checkedOrgNodes:checkedNodes });
      form.setFieldsValue({ orgStr: value});
    }else if (selectedType === 'position'){
      this.setState({ checkedPosKeys:checkedKeys, checkedPosNodes:checkedNodes });
      form.setFieldsValue({ positionStr: value});
    }else {
      if(selectUserType === 'operatorUserNames') {
        form.setFieldsValue({ operatorUserNames: value, operator: value });
      } else {
        form.setFieldsValue({ applyUserNames: value, operator: value });
      }
      this.setState({ checkedKeys, checkedNodes });
    }

  };

  renderInputButton(selectUserType, selectType, selectedName) {
    return (
      <Zcon
        onClick={() => this.setState({ overlayVisible: true,
          selectUserType: selectUserType || '' ,
          selectedType: selectType,
          selectedName})}
        style={{ color: "rgba(0,0,0,0.25)", cursor: "pointer" }}
        title="点击进行选择"
        type="down"
      />
    );
  }

  renderUserSelect(selectType) {
    const { overlayVisible, checkedKeys, checkedNodes, checkedOrgNodes, checkedOrgKeys, checkedPosNodes, checkedPosKeys, selectedName } = this.state;
    const { dispatch, userTitle } = this.props;
    let keys = checkedKeys;
    let nodes = checkedNodes;
    if (selectType ==='organ'){
      keys = checkedOrgKeys;
      nodes = checkedOrgNodes;
    } else if (selectType === 'position'){
      keys = checkedPosKeys;
      nodes = checkedPosNodes;
    }
    return (
      <UserSelectModal
        title={selectedName || userTitle}
        type={selectType||'user'}
        checkedKeys={keys}
        checkedNodes={nodes}
        dispatch={dispatch}
        onCancel={() => this.setState({ overlayVisible: false })}
        onOk={this.checkTree}
        visible={overlayVisible}
      />
    );

    /*
      const  overlay = (
        <div className={styles.overlay_root}>
          <div className={styles.header}>
            <Zcon
              onClick={() => this.setState({ overlayVisible: false })}
              style={{color: "rgba(0,0,0,0.85)", fontSize: 16, cursor: "pointer"}}
              title="关闭"
              type="close"
            />
          </div>
          <div className={styles.user}>
            <UserTree
              dispatch={dispatch}
              checkTreefunction={this.checkTree}
              checkedKeys={checkedKeys}
            />
          </div>
        </div>
      );

      const userSelect = (
        <Dropdown
          onVisibleChange={v => (v && this.setState({ overlayVisible: true }))}
          overlay={overlay}
          trigger={['click']}
          visible={overlayVisible}
        >
          <Zcon type="down" style={{color: "rgba(0,0,0,0.25)", cursor: "pointer"}} />
        </Dropdown>
      );
      return userSelect;
    */
  }

  renderFlowFilter() {
    const { form, visible } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div className={`filter__box ${!visible ? "box__hidden" : ""}`}>
        <Form layout="horizontal">
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="发起人" {...this.formItemLayout}>
                {getFieldDecorator(
                  "applyUserNames",
                  {},
                )(
                  <Input
                    placeholder="请输入发起人, 多个姓名以中文逗号分隔"
                    className="input__search"
                    suffix={this.renderInputButton()}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="发起时间" {...this.formItemLayout}>
                {getFieldDecorator("datatime", {
                  initialValue: "",
                })(
                  <RangePicker
                    format="YYYY-MM-DD HH:mm:ss"
                    className="input__search"
                    placeholder={["开始时间", "结束时间"]}
                    showTime
                    style={{ width: "100%" }}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="结束时间" {...this.formItemLayout}>
                {getFieldDecorator("endDatatime", {
                  initialValue: "",
                })(
                  <RangePicker
                    format="YYYY-MM-DD HH:mm:ss"
                    className="input__search"
                    placeholder={["开始时间", "结束时间"]}
                    showTime
                    style={{ width: "100%" }}
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="流程实例ID" {...this.formItemLayout}>
                {getFieldDecorator(
                  "processInstanceIdStr",
                  {},
                )(
                  <Input
                    placeholder="请输入流程实例ID, 多个流程实例ID以英文逗号分隔"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="当前节点名称" {...this.formItemLayout}>
                {getFieldDecorator(
                  "currentNodeName",
                  {},
                )(
                  <Input
                    placeholder="请输入当前节点名称"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="当前节点编码" {...this.formItemLayout}>
                {getFieldDecorator(
                  "currentNodeCode",
                  {},
                )(
                  <Input
                    placeholder="请输入当前节点编码"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="当前处理人" {...this.formItemLayout}>
                {getFieldDecorator(
                  "operatorUserNames",
                  {},
                )(
                  <Input
                    placeholder="请输入当前处理人, 多个姓名以中文逗号分隔"
                    className="input__search"
                    suffix={this.renderInputButton('operatorUserNames')}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="环节" {...this.formItemLayout}>
                {getFieldDecorator("linkStatus", {
                  // initialValue: '',
                })(
                  <Select placeholder="请选择环节">
                    {progressConfig.map(({ label, value }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="状态" {...this.formItemLayout}>
                {getFieldDecorator("status", {
                  // initialValue: '',
                })(
                  <Select placeholder="请选择状态">
                    {statusConfig.map(({ label, value }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="版本" {...this.formItemLayout}>
                {getFieldDecorator("version", {
                  rules: [
                    {
                      pattern: /^([1-9][0-9]*)$/,
                      message: "请输入正整数",
                    },
                  ],
                })(
                  <Input placeholder="请输入版本" className="input__search" />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <div className="filter_buttons">
                <Button type="primary" size="small" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button size="small" onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

  renderTaskFilter() {
    const { form, visible } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div className={`filter__box ${!visible ? "box__hidden" : ""}`}>
        <Form layout="horizontal">
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="处理人" {...this.formItemLayout}>
                {getFieldDecorator(
                  "applyUserNames",
                  {},
                )(
                  <Input
                    placeholder="请输入处理人, 多个姓名以中文逗号分割"
                    className="input__search"
                    suffix={this.renderInputButton()}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="任务状态" {...this.formItemLayout}>
                {getFieldDecorator("status", {
                  // initialValue: '',
                })(
                  <Select placeholder="请选择状态">
                    {statusConfig.map(({ label, value }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="任务环节" {...this.formItemLayout}>
                {getFieldDecorator("linkStatus", {
                  // initialValue: '',
                })(
                  <Select placeholder="请选择环节">
                    {taskConfig.map(({ label, value }) => (
                      <Option key={value} value={value}>
                        {label}
                      </Option>
                    ))}
                  </Select>,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="流程实例ID" {...this.formItemLayout}>
                {getFieldDecorator(
                  "processInstanceIdStr",
                  {},
                )(
                  <Input
                    placeholder="请输入流程实例ID, 多个流程实例ID以英文逗号分隔"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="流程名称" {...this.formItemLayout}>
                {getFieldDecorator(
                  "modelName",
                  {},
                )(
                  <Input
                    placeholder="请输入流程名称"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="工号" {...this.formItemLayout}>
                {getFieldDecorator(
                  "employeeCode",
                  {},
                )(
                  <Input
                    placeholder="请输入工号"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="角色" {...this.formItemLayout}>
                {getFieldDecorator(
                  "roleIdStr",
                  {},
                )(
                  <CustomTreeSelectField type="ROL" multiple placeholder="请输入角色" />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="组织" {...this.formItemLayout}>
                {getFieldDecorator(
                  "orgStr",
                  {},
                )(
                  <Input
                    placeholder="请输入组织"
                    className="input__search"
                    suffix={this.renderInputButton('','organ','组织')}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="岗位" {...this.formItemLayout}>
                {getFieldDecorator(
                  "positionStr",
                  {},
                )(
                  <Input
                    placeholder="请输入岗位"
                    className="input__search"
                    // suffix={this.renderInputButton('','position','岗位')}
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="任务ID" {...this.formItemLayout}>
                {getFieldDecorator(
                  "taskIdStr",
                  {},
                )(
                  <Input
                    placeholder="请输入任务ID，多个ID用英文逗号分割"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <div className="filter_buttons">
                <Button type="primary" size="small" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button size="small" onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

  renderRuleFilter() {
    const { form, visible } = this.props;
    const { getFieldDecorator } = form;

    return (
      <div className={`filter__box ${!visible ? "box__hidden" : ""}`}>
        <Form layout="horizontal">
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="操作人" {...this.formItemLayout}>
                {getFieldDecorator(
                  "operator",
                  {},
                )(
                  <Input
                    placeholder="请输入处理人, 多个姓名以中文逗号分割"
                    className="input__search"
                    suffix={this.renderInputButton()}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="操作日期" {...this.formItemLayout}>
                {getFieldDecorator("datatime", {
                  initialValue: "",
                })(
                  <RangePicker
                    format="YYYY-MM-DD HH:mm:ss"
                    className="input__search"
                    placeholder={["开始时间", "结束时间"]}
                    showTime
                    style={{ width: "100%" }}
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item label="流程名称" {...this.formItemLayout}>
                {getFieldDecorator(
                  "modelName",
                  {},
                )(
                  <Input
                    placeholder="请输入流程名称"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
          </Row>
          <Row
            className={`filter_form_box ${styles.filter_b_box} ${styles.lbl_w}`}
          >
            <Col span={8}>
              <Form.Item label="流程标识" {...this.formItemLayout}>
                {getFieldDecorator(
                  "modelId",
                  {},
                )(
                  <Input
                    placeholder="请输入流程标识"
                    className="input__search"
                  />,
                )}
              </Form.Item>
            </Col>
            <Col span={16}>
              <div className="filter_buttons">
                <Button type="primary" size="small" onClick={this.handleSearch}>
                  查询
                </Button>
                <Button size="small" onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>
    );
  }

  render() {
    // renderType: flow 流程 task 任务
    const { renderType = "flow" } = this.props;
    const { selectedType = "user"} = this.state;
    return (
      <>
        {renderType === "flow"
          ? this.renderFlowFilter()
          : renderType === "task"
          ? this.renderTaskFilter()
          : this.renderRuleFilter()}
        {this.renderUserSelect(selectedType)}
      </>
    );
  }
}

export default AdvancedFilter;
